package cms_article

import (
	"fmt"
	"gitee.com/binny_w/gin_starter/model/cms_category"
	"github.com/gin-gonic/gin"
	"strings"
)

func queryFixer(c *gin.Context, k string, v []string, p []any) (w, k1 string, p1 []any, ctn bool, err error) {
	err = fmt.Errorf("key not match")
	k1 = k
	p1 = p
	switch k {
	case "deleted_at[]":
		k1 = "deleted_at"
		err = nil
		ctn = true
		if len(v) == 1 {
			if v[0] == "0" {
				w = fmt.Sprintf("and `%s` = 0", k1)
			} else {
				w = fmt.Sprintf("and `%s` > 0", k1)
			}
		}
	case "id":
		err = nil
		qid := c.Query("id")
		ctn = qid == "0" || qid == ""
	case "category":
		err = nil
		k1 = "category_key"
		ctn = true
		if len(v) == 1 && v[0] != "" {
			if v[0] == "-" {
				w = fmt.Sprintf("and `%s` = ''", k1)
			} else {
				tree, _ := cms_category.Tree(c)
				ss := tree.ChildrenKeys(v[0])
				if len(ss) == 0 {
					w = fmt.Sprintf("and `%s` = ?", k1)
					p1 = append(p1, v[0])
					return
				}
				ss = append(ss, v[0])
				q := ""
				for _, s := range ss {
					q += "?,"
					p1 = append(p1, s)
				}
				w = fmt.Sprintf("and `%s` in (%s)", k1, strings.TrimRight(q, ","))
			}
		}
	}
	return
}
